﻿using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace TddBarForPhone
{
    public class ConsoleTddPainter
    {
        public static void WriteLine(string line)
        {
            SetConsoleColor(line);
            Console.WriteLine(line);
            Console.ResetColor();
        }

        private static void SetConsoleColor(string line)
        {
            if (String.IsNullOrEmpty(line))
            {
                return;
            }

            if (Regex.IsMatch(line, "Tests run:", RegexOptions.IgnoreCase))
            {
                bool thereIsFailuresOrErrors = (
                                                   from Match m in
                                                       new Regex(@"(failures|errors): (\d+)", RegexOptions.IgnoreCase).
                                                       Matches(line)
                                                   select int.Parse(m.Groups[2].Value)
                                               ).Any(nb => nb != 0);
                if (thereIsFailuresOrErrors)
                {
                    PaintRed();
                }
                else
                {
                    PaintGreen();
                }
                return;
            }
        }

        private static void PaintGreen()
        {
            Console.ForegroundColor = ConsoleColor.Green;
        }

        private static void PaintRed()
        {
            Console.ForegroundColor = ConsoleColor.Red;
        }
    }
}
